package com.atguigu.juc.date108;

import org.openjdk.jol.info.ClassLayout;

/**
 * @Author: shenhao
 * @CreatTime: 2024/10/8 19:17
 * @Version: 1.0
 * 锁膨胀机制: 无锁状态 non-biasable 当前 JVM 没有开启偏向锁功能, biasable
 * 偏向锁状态 biased,
 * 轻量锁状态 thin lock,
 * 重量锁状态 fat lock
 *
 * 先配置JVM参数：
 *  *
 *  * #开启偏向锁
 *  * -XX:+UseBiasedLocking
 *  *
 *  * #关闭偏向锁有延时
 *  * -XX:BiasedLockingStartupDelay=0
 */
public class LockUpDemo {
    public static void main(String[] args) {
        //biasable();
        //biased();
        //thin();
        fat();
    }
    /**
     *测试04
     * 升级至重量级锁的代码
     */
    private static void fat() {
        // 1、创建一个对象作为锁对象
        Object lock = new Object();
        // 2、没有线程申请锁
        System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        // 3、同一个Main线程多次申请锁
        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
        Thread thread1=new Thread(()->{
            synchronized (lock) {
                System.out.println(ClassLayout.parseInstance(lock).toPrintable());
            }
        },"thread-a");
        thread1.start();
        Thread thread2 =new Thread(()->{
            synchronized (lock) {
                System.out.println(ClassLayout.parseInstance(lock).toPrintable());
            }
        },"thread-b");
        thread2.start();
    }

    /**
     * 测试03
     * 偏向锁 → 轻量级锁
     */
    private static void thin() {
        // 1、创建一个对象作为锁对象
        Object lock = new Object();
        // 2、没有线程申请锁
        System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        // 3、同一个Main线程多次申请锁
        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
        Thread thread1=new Thread(()->{
            synchronized (lock) {
                System.out.println(ClassLayout.parseInstance(lock).toPrintable());
            }
        },"thread-a");
        thread1.start();
    }

    /**
     * 测试02
     * 从可偏向，意思是当前 JVM 开启了偏向锁功能（此时锁的状态是无锁状态)  到 偏向锁
     * 无锁状态 → 偏向锁
     */
    private static void biased() {
        // 1、创建一个对象作为锁对象
        Object lock = new Object();
        // 2、没有线程申请锁
        System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        // 3、main 线程申请锁
        synchronized (lock) {
            System.out.println(ClassLayout.parseInstance(lock).toPrintable());
        }
    }
    /** JOL = java Object Layout
     * 测试01
     * 可偏向，意思是当前 JVM 开启了偏向锁功能（此时锁的状态是无锁状态）
     */
    private static void biasable() {
        Object lock = new Object();
        System.out.println(ClassLayout.parseInstance(lock).toPrintable());
    }
}
